package permission_pb

import (
	context "context"
	fmt "fmt"
	gorm1 "github.com/infobloxopen/atlas-app-toolkit/gorm"
	query "github.com/infobloxopen/atlas-app-toolkit/query"
	errors "github.com/infobloxopen/protoc-gen-gorm/errors"
	gorm "github.com/jinzhu/gorm"
	field_mask "google.golang.org/genproto/protobuf/field_mask"
	timestamppb "google.golang.org/protobuf/types/known/timestamppb"
	strings "strings"
	time "time"
)

type ApiORM struct {
	ApiGroup    string
	CreatedAt   *time.Time
	Description string
	Id          uint64
	Method      string `gorm:"default:POST"`
	Path        string
	UpdatedAt   *time.Time
}

// TableName overrides the default tablename generated by GORM
func (ApiORM) TableName() string {
	return "apis"
}

// ToORM runs the BeforeToORM hook if present, converts the fields of this
// object to ORM format, runs the AfterToORM hook, then returns the ORM object
func (m *Api) ToORM(ctx context.Context) (ApiORM, error) {
	to := ApiORM{}
	var err error
	if prehook, ok := interface{}(m).(ApiWithBeforeToORM); ok {
		if err = prehook.BeforeToORM(ctx, &to); err != nil {
			return to, err
		}
	}
	to.Id = m.Id
	if m.CreatedAt != nil {
		t := m.CreatedAt.AsTime()
		to.CreatedAt = &t
	}
	if m.UpdatedAt != nil {
		t := m.UpdatedAt.AsTime()
		to.UpdatedAt = &t
	}
	to.Path = m.Path
	to.Description = m.Description
	to.ApiGroup = m.ApiGroup
	to.Method = m.Method
	if posthook, ok := interface{}(m).(ApiWithAfterToORM); ok {
		err = posthook.AfterToORM(ctx, &to)
	}
	return to, err
}

// ToPB runs the BeforeToPB hook if present, converts the fields of this
// object to PB format, runs the AfterToPB hook, then returns the PB object
func (m *ApiORM) ToPB(ctx context.Context) (Api, error) {
	to := Api{}
	var err error
	if prehook, ok := interface{}(m).(ApiWithBeforeToPB); ok {
		if err = prehook.BeforeToPB(ctx, &to); err != nil {
			return to, err
		}
	}
	to.Id = m.Id
	if m.CreatedAt != nil {
		to.CreatedAt = timestamppb.New(*m.CreatedAt)
	}
	if m.UpdatedAt != nil {
		to.UpdatedAt = timestamppb.New(*m.UpdatedAt)
	}
	to.Path = m.Path
	to.Description = m.Description
	to.ApiGroup = m.ApiGroup
	to.Method = m.Method
	if posthook, ok := interface{}(m).(ApiWithAfterToPB); ok {
		err = posthook.AfterToPB(ctx, &to)
	}
	return to, err
}

// The following are interfaces you can implement for special behavior during ORM/PB conversions
// of type Api the arg will be the target, the caller the one being converted from

// ApiBeforeToORM called before default ToORM code
type ApiWithBeforeToORM interface {
	BeforeToORM(context.Context, *ApiORM) error
}

// ApiAfterToORM called after default ToORM code
type ApiWithAfterToORM interface {
	AfterToORM(context.Context, *ApiORM) error
}

// ApiBeforeToPB called before default ToPB code
type ApiWithBeforeToPB interface {
	BeforeToPB(context.Context, *Api) error
}

// ApiAfterToPB called after default ToPB code
type ApiWithAfterToPB interface {
	AfterToPB(context.Context, *Api) error
}

// DefaultCreateApi executes a basic gorm create call
func DefaultCreateApi(ctx context.Context, in *Api, db *gorm.DB) (*Api, error) {
	if in == nil {
		return nil, errors.NilArgumentError
	}
	ormObj, err := in.ToORM(ctx)
	if err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeCreate_); ok {
		if db, err = hook.BeforeCreate_(ctx, db); err != nil {
			return nil, err
		}
	}
	if err = db.Create(&ormObj).Error; err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithAfterCreate_); ok {
		if err = hook.AfterCreate_(ctx, db); err != nil {
			return nil, err
		}
	}
	pbResponse, err := ormObj.ToPB(ctx)
	return &pbResponse, err
}

type ApiORMWithBeforeCreate_ interface {
	BeforeCreate_(context.Context, *gorm.DB) (*gorm.DB, error)
}
type ApiORMWithAfterCreate_ interface {
	AfterCreate_(context.Context, *gorm.DB) error
}

func DefaultReadApi(ctx context.Context, in *Api, db *gorm.DB, fs *query.FieldSelection) (*Api, error) {
	if in == nil {
		return nil, errors.NilArgumentError
	}
	ormObj, err := in.ToORM(ctx)
	if err != nil {
		return nil, err
	}
	if ormObj.Id == 0 {
		return nil, errors.EmptyIdError
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeReadApplyQuery); ok {
		if db, err = hook.BeforeReadApplyQuery(ctx, db, fs); err != nil {
			return nil, err
		}
	}
	if db, err = gorm1.ApplyFieldSelection(ctx, db, fs, &ApiORM{}); err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeReadFind); ok {
		if db, err = hook.BeforeReadFind(ctx, db, fs); err != nil {
			return nil, err
		}
	}
	ormResponse := ApiORM{}
	if err = db.Where(&ormObj).First(&ormResponse).Error; err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormResponse).(ApiORMWithAfterReadFind); ok {
		if err = hook.AfterReadFind(ctx, db, fs); err != nil {
			return nil, err
		}
	}
	pbResponse, err := ormResponse.ToPB(ctx)
	return &pbResponse, err
}

type ApiORMWithBeforeReadApplyQuery interface {
	BeforeReadApplyQuery(context.Context, *gorm.DB, *query.FieldSelection) (*gorm.DB, error)
}
type ApiORMWithBeforeReadFind interface {
	BeforeReadFind(context.Context, *gorm.DB, *query.FieldSelection) (*gorm.DB, error)
}
type ApiORMWithAfterReadFind interface {
	AfterReadFind(context.Context, *gorm.DB, *query.FieldSelection) error
}

func DefaultDeleteApi(ctx context.Context, in *Api, db *gorm.DB) error {
	if in == nil {
		return errors.NilArgumentError
	}
	ormObj, err := in.ToORM(ctx)
	if err != nil {
		return err
	}
	if ormObj.Id == 0 {
		return errors.EmptyIdError
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeDelete_); ok {
		if db, err = hook.BeforeDelete_(ctx, db); err != nil {
			return err
		}
	}
	err = db.Where(&ormObj).Delete(&ApiORM{}).Error
	if err != nil {
		return err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithAfterDelete_); ok {
		err = hook.AfterDelete_(ctx, db)
	}
	return err
}

type ApiORMWithBeforeDelete_ interface {
	BeforeDelete_(context.Context, *gorm.DB) (*gorm.DB, error)
}
type ApiORMWithAfterDelete_ interface {
	AfterDelete_(context.Context, *gorm.DB) error
}

func DefaultDeleteApiSet(ctx context.Context, in []*Api, db *gorm.DB) error {
	if in == nil {
		return errors.NilArgumentError
	}
	var err error
	keys := []uint64{}
	for _, obj := range in {
		ormObj, err := obj.ToORM(ctx)
		if err != nil {
			return err
		}
		if ormObj.Id == 0 {
			return errors.EmptyIdError
		}
		keys = append(keys, ormObj.Id)
	}
	if hook, ok := (interface{}(&ApiORM{})).(ApiORMWithBeforeDeleteSet); ok {
		if db, err = hook.BeforeDeleteSet(ctx, in, db); err != nil {
			return err
		}
	}
	err = db.Where("id in (?)", keys).Delete(&ApiORM{}).Error
	if err != nil {
		return err
	}
	if hook, ok := (interface{}(&ApiORM{})).(ApiORMWithAfterDeleteSet); ok {
		err = hook.AfterDeleteSet(ctx, in, db)
	}
	return err
}

type ApiORMWithBeforeDeleteSet interface {
	BeforeDeleteSet(context.Context, []*Api, *gorm.DB) (*gorm.DB, error)
}
type ApiORMWithAfterDeleteSet interface {
	AfterDeleteSet(context.Context, []*Api, *gorm.DB) error
}

// DefaultStrictUpdateApi clears / replaces / appends first level 1:many children and then executes a gorm update call
func DefaultStrictUpdateApi(ctx context.Context, in *Api, db *gorm.DB) (*Api, error) {
	if in == nil {
		return nil, fmt.Errorf("Nil argument to DefaultStrictUpdateApi")
	}
	ormObj, err := in.ToORM(ctx)
	if err != nil {
		return nil, err
	}
	lockedRow := &ApiORM{}
	db.Model(&ormObj).Set("gorm:query_option", "FOR UPDATE").Where("id=?", ormObj.Id).First(lockedRow)
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeStrictUpdateCleanup); ok {
		if db, err = hook.BeforeStrictUpdateCleanup(ctx, db); err != nil {
			return nil, err
		}
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeStrictUpdateSave); ok {
		if db, err = hook.BeforeStrictUpdateSave(ctx, db); err != nil {
			return nil, err
		}
	}
	if err = db.Save(&ormObj).Error; err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithAfterStrictUpdateSave); ok {
		if err = hook.AfterStrictUpdateSave(ctx, db); err != nil {
			return nil, err
		}
	}
	pbResponse, err := ormObj.ToPB(ctx)
	if err != nil {
		return nil, err
	}
	return &pbResponse, err
}

type ApiORMWithBeforeStrictUpdateCleanup interface {
	BeforeStrictUpdateCleanup(context.Context, *gorm.DB) (*gorm.DB, error)
}
type ApiORMWithBeforeStrictUpdateSave interface {
	BeforeStrictUpdateSave(context.Context, *gorm.DB) (*gorm.DB, error)
}
type ApiORMWithAfterStrictUpdateSave interface {
	AfterStrictUpdateSave(context.Context, *gorm.DB) error
}

// DefaultPatchApi executes a basic gorm update call with patch behavior
func DefaultPatchApi(ctx context.Context, in *Api, updateMask *field_mask.FieldMask, db *gorm.DB) (*Api, error) {
	if in == nil {
		return nil, errors.NilArgumentError
	}
	var pbObj Api
	var err error
	if hook, ok := interface{}(&pbObj).(ApiWithBeforePatchRead); ok {
		if db, err = hook.BeforePatchRead(ctx, in, updateMask, db); err != nil {
			return nil, err
		}
	}
	pbReadRes, err := DefaultReadApi(ctx, &Api{Id: in.GetId()}, db, nil)
	if err != nil {
		return nil, err
	}
	pbObj = *pbReadRes
	if hook, ok := interface{}(&pbObj).(ApiWithBeforePatchApplyFieldMask); ok {
		if db, err = hook.BeforePatchApplyFieldMask(ctx, in, updateMask, db); err != nil {
			return nil, err
		}
	}
	if _, err := DefaultApplyFieldMaskApi(ctx, &pbObj, in, updateMask, "", db); err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&pbObj).(ApiWithBeforePatchSave); ok {
		if db, err = hook.BeforePatchSave(ctx, in, updateMask, db); err != nil {
			return nil, err
		}
	}
	pbResponse, err := DefaultStrictUpdateApi(ctx, &pbObj, db)
	if err != nil {
		return nil, err
	}
	if hook, ok := interface{}(pbResponse).(ApiWithAfterPatchSave); ok {
		if err = hook.AfterPatchSave(ctx, in, updateMask, db); err != nil {
			return nil, err
		}
	}
	return pbResponse, nil
}

type ApiWithBeforePatchRead interface {
	BeforePatchRead(context.Context, *Api, *field_mask.FieldMask, *gorm.DB) (*gorm.DB, error)
}
type ApiWithBeforePatchApplyFieldMask interface {
	BeforePatchApplyFieldMask(context.Context, *Api, *field_mask.FieldMask, *gorm.DB) (*gorm.DB, error)
}
type ApiWithBeforePatchSave interface {
	BeforePatchSave(context.Context, *Api, *field_mask.FieldMask, *gorm.DB) (*gorm.DB, error)
}
type ApiWithAfterPatchSave interface {
	AfterPatchSave(context.Context, *Api, *field_mask.FieldMask, *gorm.DB) error
}

// DefaultPatchSetApi executes a bulk gorm update call with patch behavior
func DefaultPatchSetApi(ctx context.Context, objects []*Api, updateMasks []*field_mask.FieldMask, db *gorm.DB) ([]*Api, error) {
	if len(objects) != len(updateMasks) {
		return nil, fmt.Errorf(errors.BadRepeatedFieldMaskTpl, len(updateMasks), len(objects))
	}

	results := make([]*Api, 0, len(objects))
	for i, patcher := range objects {
		pbResponse, err := DefaultPatchApi(ctx, patcher, updateMasks[i], db)
		if err != nil {
			return nil, err
		}

		results = append(results, pbResponse)
	}

	return results, nil
}

// DefaultApplyFieldMaskApi patches an pbObject with patcher according to a field mask.
func DefaultApplyFieldMaskApi(ctx context.Context, patchee *Api, patcher *Api, updateMask *field_mask.FieldMask, prefix string, db *gorm.DB) (*Api, error) {
	if patcher == nil {
		return nil, nil
	} else if patchee == nil {
		return nil, errors.NilArgumentError
	}
	var err error
	var updatedCreatedAt bool
	var updatedUpdatedAt bool
	for i, f := range updateMask.Paths {
		if f == prefix+"Id" {
			patchee.Id = patcher.Id
			continue
		}
		if !updatedCreatedAt && strings.HasPrefix(f, prefix+"CreatedAt.") {
			if patcher.CreatedAt == nil {
				patchee.CreatedAt = nil
				continue
			}
			if patchee.CreatedAt == nil {
				patchee.CreatedAt = &timestamppb.Timestamp{}
			}
			childMask := &field_mask.FieldMask{}
			for j := i; j < len(updateMask.Paths); j++ {
				if trimPath := strings.TrimPrefix(updateMask.Paths[j], prefix+"CreatedAt."); trimPath != updateMask.Paths[j] {
					childMask.Paths = append(childMask.Paths, trimPath)
				}
			}
			if err := gorm1.MergeWithMask(patcher.CreatedAt, patchee.CreatedAt, childMask); err != nil {
				return nil, nil
			}
		}
		if f == prefix+"CreatedAt" {
			updatedCreatedAt = true
			patchee.CreatedAt = patcher.CreatedAt
			continue
		}
		if !updatedUpdatedAt && strings.HasPrefix(f, prefix+"UpdatedAt.") {
			if patcher.UpdatedAt == nil {
				patchee.UpdatedAt = nil
				continue
			}
			if patchee.UpdatedAt == nil {
				patchee.UpdatedAt = &timestamppb.Timestamp{}
			}
			childMask := &field_mask.FieldMask{}
			for j := i; j < len(updateMask.Paths); j++ {
				if trimPath := strings.TrimPrefix(updateMask.Paths[j], prefix+"UpdatedAt."); trimPath != updateMask.Paths[j] {
					childMask.Paths = append(childMask.Paths, trimPath)
				}
			}
			if err := gorm1.MergeWithMask(patcher.UpdatedAt, patchee.UpdatedAt, childMask); err != nil {
				return nil, nil
			}
		}
		if f == prefix+"UpdatedAt" {
			updatedUpdatedAt = true
			patchee.UpdatedAt = patcher.UpdatedAt
			continue
		}
		if f == prefix+"Path" {
			patchee.Path = patcher.Path
			continue
		}
		if f == prefix+"Description" {
			patchee.Description = patcher.Description
			continue
		}
		if f == prefix+"ApiGroup" {
			patchee.ApiGroup = patcher.ApiGroup
			continue
		}
		if f == prefix+"Method" {
			patchee.Method = patcher.Method
			continue
		}
	}
	if err != nil {
		return nil, err
	}
	return patchee, nil
}

// DefaultListApi executes a gorm list call
func DefaultListApi(ctx context.Context, db *gorm.DB, f *query.Filtering, s *query.Sorting, p *query.Pagination, fs *query.FieldSelection) ([]*Api, error) {
	in := Api{}
	ormObj, err := in.ToORM(ctx)
	if err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeListApplyQuery); ok {
		if db, err = hook.BeforeListApplyQuery(ctx, db, f, s, p, fs); err != nil {
			return nil, err
		}
	}
	db, err = gorm1.ApplyCollectionOperators(ctx, db, &ApiORM{}, &Api{}, f, s, p, fs)
	if err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithBeforeListFind); ok {
		if db, err = hook.BeforeListFind(ctx, db, f, s, p, fs); err != nil {
			return nil, err
		}
	}
	db = db.Where(&ormObj)
	db = db.Order("id")
	ormResponse := []ApiORM{}
	if err := db.Find(&ormResponse).Error; err != nil {
		return nil, err
	}
	if hook, ok := interface{}(&ormObj).(ApiORMWithAfterListFind); ok {
		if err = hook.AfterListFind(ctx, db, &ormResponse, f, s, p, fs); err != nil {
			return nil, err
		}
	}
	pbResponse := []*Api{}
	for _, responseEntry := range ormResponse {
		temp, err := responseEntry.ToPB(ctx)
		if err != nil {
			return nil, err
		}
		pbResponse = append(pbResponse, &temp)
	}
	return pbResponse, nil
}

type ApiORMWithBeforeListApplyQuery interface {
	BeforeListApplyQuery(context.Context, *gorm.DB, *query.Filtering, *query.Sorting, *query.Pagination, *query.FieldSelection) (*gorm.DB, error)
}
type ApiORMWithBeforeListFind interface {
	BeforeListFind(context.Context, *gorm.DB, *query.Filtering, *query.Sorting, *query.Pagination, *query.FieldSelection) (*gorm.DB, error)
}
type ApiORMWithAfterListFind interface {
	AfterListFind(context.Context, *gorm.DB, *[]ApiORM, *query.Filtering, *query.Sorting, *query.Pagination, *query.FieldSelection) error
}
type ApiServiceDefaultServer struct {
	DB *gorm.DB
}

// Create ...
func (m *ApiServiceDefaultServer) Create(ctx context.Context, in *CreateApiRequest) (*CreateApiResponse, error) {
	db := m.DB
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeCreate); ok {
		var err error
		if db, err = custom.BeforeCreate(ctx, db); err != nil {
			return nil, err
		}
	}
	res, err := DefaultCreateApi(ctx, in.GetPayload(), db)
	if err != nil {
		return nil, err
	}
	out := &CreateApiResponse{Result: res}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterCreate); ok {
		var err error
		if err = custom.AfterCreate(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeCreate called before DefaultCreateApi in the default Create handler
type ApiServiceApiWithBeforeCreate interface {
	BeforeCreate(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterCreate called before DefaultCreateApi in the default Create handler
type ApiServiceApiWithAfterCreate interface {
	AfterCreate(context.Context, *CreateApiResponse, *gorm.DB) error
}

// Read ...
func (m *ApiServiceDefaultServer) Read(ctx context.Context, in *ReadApiRequest) (*ReadApiResponse, error) {
	db := m.DB
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeRead); ok {
		var err error
		if db, err = custom.BeforeRead(ctx, db); err != nil {
			return nil, err
		}
	}
	res, err := DefaultReadApi(ctx, &Api{Id: in.GetId()}, db, in.Fields)
	if err != nil {
		return nil, err
	}
	out := &ReadApiResponse{Result: res}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterRead); ok {
		var err error
		if err = custom.AfterRead(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeRead called before DefaultReadApi in the default Read handler
type ApiServiceApiWithBeforeRead interface {
	BeforeRead(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterRead called before DefaultReadApi in the default Read handler
type ApiServiceApiWithAfterRead interface {
	AfterRead(context.Context, *ReadApiResponse, *gorm.DB) error
}

// Update ...
func (m *ApiServiceDefaultServer) Update(ctx context.Context, in *UpdateApiRequest) (*UpdateApiResponse, error) {
	var err error
	var res *Api
	db := m.DB
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeUpdate); ok {
		var err error
		if db, err = custom.BeforeUpdate(ctx, db); err != nil {
			return nil, err
		}
	}
	if in.GetGerogeriGegege() == nil {
		res, err = DefaultStrictUpdateApi(ctx, in.GetPayload(), db)
	} else {
		res, err = DefaultPatchApi(ctx, in.GetPayload(), in.GetGerogeriGegege(), db)
	}
	if err != nil {
		return nil, err
	}
	out := &UpdateApiResponse{Result: res}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterUpdate); ok {
		var err error
		if err = custom.AfterUpdate(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeUpdate called before DefaultUpdateApi in the default Update handler
type ApiServiceApiWithBeforeUpdate interface {
	BeforeUpdate(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterUpdate called before DefaultUpdateApi in the default Update handler
type ApiServiceApiWithAfterUpdate interface {
	AfterUpdate(context.Context, *UpdateApiResponse, *gorm.DB) error
}

// UpdateSet ...
func (m *ApiServiceDefaultServer) UpdateSet(ctx context.Context, in *UpdateSetApiRequest) (*UpdateSetApiResponse, error) {
	if in == nil {
		return nil, errors.NilArgumentError
	}

	db := m.DB

	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeUpdateSet); ok {
		var err error
		if db, err = custom.BeforeUpdateSet(ctx, db); err != nil {
			return nil, err
		}
	}

	res, err := DefaultPatchSetApi(ctx, in.GetObjects(), in.GetMasks(), db)
	if err != nil {
		return nil, err
	}

	out := &UpdateSetApiResponse{Results: res}

	if custom, ok := interface{}(in).(ApiServiceApiWithAfterUpdateSet); ok {
		var err error
		if err = custom.AfterUpdateSet(ctx, out, db); err != nil {
			return nil, err
		}
	}

	return out, nil
}

// ApiServiceApiWithBeforeUpdateSet called before DefaultUpdateSetApi in the default UpdateSet handler
type ApiServiceApiWithBeforeUpdateSet interface {
	BeforeUpdateSet(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterUpdateSet called before DefaultUpdateSetApi in the default UpdateSet handler
type ApiServiceApiWithAfterUpdateSet interface {
	AfterUpdateSet(context.Context, *UpdateSetApiResponse, *gorm.DB) error
}

// List ...
func (m *ApiServiceDefaultServer) List(ctx context.Context, in *ListApiRequest) (*ListApiResponse, error) {
	db := m.DB
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeList); ok {
		var err error
		if db, err = custom.BeforeList(ctx, db); err != nil {
			return nil, err
		}
	}
	pagedRequest := false
	if in.GetPaging().GetLimit() >= 1 {
		in.Paging.Limit++
		pagedRequest = true
	}
	res, err := DefaultListApi(ctx, db, in.Filter, in.OrderBy, in.Paging, in.Fields)
	if err != nil {
		return nil, err
	}
	var resPaging *query.PageInfo
	if pagedRequest {
		var offset int32
		var size int32 = int32(len(res))
		if size == in.GetPaging().GetLimit() {
			size--
			res = res[:size]
			offset = in.GetPaging().GetOffset() + size
		}
		resPaging = &query.PageInfo{Offset: offset}
	}
	out := &ListApiResponse{Results: res, PageInfo: resPaging}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterList); ok {
		var err error
		if err = custom.AfterList(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeList called before DefaultListApi in the default List handler
type ApiServiceApiWithBeforeList interface {
	BeforeList(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterList called before DefaultListApi in the default List handler
type ApiServiceApiWithAfterList interface {
	AfterList(context.Context, *ListApiResponse, *gorm.DB) error
}

// Delete ...
func (m *ApiServiceDefaultServer) Delete(ctx context.Context, in *DeleteApiRequest) (*DeleteApiResponse, error) {
	db := m.DB
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeDelete); ok {
		var err error
		if db, err = custom.BeforeDelete(ctx, db); err != nil {
			return nil, err
		}
	}
	err := DefaultDeleteApi(ctx, &Api{Id: in.GetId()}, db)
	if err != nil {
		return nil, err
	}
	out := &DeleteApiResponse{}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterDelete); ok {
		var err error
		if err = custom.AfterDelete(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeDelete called before DefaultDeleteApi in the default Delete handler
type ApiServiceApiWithBeforeDelete interface {
	BeforeDelete(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterDelete called before DefaultDeleteApi in the default Delete handler
type ApiServiceApiWithAfterDelete interface {
	AfterDelete(context.Context, *DeleteApiResponse, *gorm.DB) error
}

// DeleteSet ...
func (m *ApiServiceDefaultServer) DeleteSet(ctx context.Context, in *DeleteSetApiRequest) (*DeleteApiResponse, error) {
	db := m.DB
	objs := []*Api{}
	for _, id := range in.Ids {
		objs = append(objs, &Api{Id: id})
	}
	if custom, ok := interface{}(in).(ApiServiceApiWithBeforeDeleteSet); ok {
		var err error
		if db, err = custom.BeforeDeleteSet(ctx, db); err != nil {
			return nil, err
		}
	}
	err := DefaultDeleteApiSet(ctx, objs, db)
	if err != nil {
		return nil, err
	}
	out := &DeleteApiResponse{}
	if custom, ok := interface{}(in).(ApiServiceApiWithAfterDeleteSet); ok {
		var err error
		if err = custom.AfterDeleteSet(ctx, out, db); err != nil {
			return nil, err
		}
	}
	return out, nil
}

// ApiServiceApiWithBeforeDeleteSet called before DefaultDeleteSetApi in the default DeleteSet handler
type ApiServiceApiWithBeforeDeleteSet interface {
	BeforeDeleteSet(context.Context, *gorm.DB) (*gorm.DB, error)
}

// ApiServiceApiWithAfterDeleteSet called before DefaultDeleteSetApi in the default DeleteSet handler
type ApiServiceApiWithAfterDeleteSet interface {
	AfterDeleteSet(context.Context, *DeleteApiResponse, *gorm.DB) error
}
